from fastapi import APIRouter, Depends, Form, HTTPException
from sqlalchemy.orm import Session

import models
import schemas
from db import get_db



router = APIRouter(prefix="/api/dictionary", tags=["词典"])



@router.post("/add")
def add_dictionary(data: schemas.DictionaryAdd, db: Session = Depends(get_db)):
    existing_en = db.query(models.dictionary).filter(models.dictionary.EN == data.EN).first()
    if existing_en:
        raise HTTPException(status_code=400, detail="EN word already exists")
    existing_zh = db.query(models.dictionary).filter(models.dictionary.ZH == data.ZH).first()
    if existing_zh:
        raise HTTPException(status_code=400, detail="ZH translation already exists")
    existing_uy = db.query(models.dictionary).filter(models.dictionary.UY == data.UY).first()
    if existing_uy:
        raise HTTPException(status_code=400, detail="UY translation already exists")

    new_dictionary = models.dictionary(EN=data.EN, ZH=data.ZH, UY=data.UY)
    db.add(new_dictionary)
    db.commit()
    db.refresh(new_dictionary)
    return new_dictionary




@router.delete("/delete/{id}")
def delete_dictionary(id: int, db: Session = Depends(get_db)):
    # Check if the dictionary item exists
    dictionary_item = db.query(models.dictionary).filter(models.dictionary.id == id).first()
    if not dictionary_item:
        raise HTTPException(status_code=404, detail="找不到结果！")

    # Delete the dictionary item
    db.delete(dictionary_item)
    db.commit()
    return {"detail": "删除成功！"}
